<template>
	<div ref="chartRef" class="w-full h-full"></div>
</template>

<script setup lang="ts" name="lineChartHistory">
import { tryOnUnmounted, useDebounceFn } from '@vueuse/core';
import * as echarts from 'echarts';
import { useEventListener } from '/@/hooks/event/useEventListener';
const props = defineProps({
	seriesData: {
		type: Array,
		default: () => [],
	},
	xAxisData: {
		type: Array,
		default: () => [],
	},
	zoomLock: {
		type: Boolean,
		default: true,
	},
	name: {
		type: String,
		default: '',
	},
});
const chartRef = ref();
let resizeFnPollute = resize;
let removeResizeFn = () => {};
let instance: any;
resizeFnPollute = useDebounceFn(resize, 200);
watch(
	() => props.seriesData,
	(val) => {
		setOptions();
	},
	{
		deep: true,
	}
);
const options = {
	grid: { bottom: '10', top: '30', right: '60', left: '60', containLabel: true },
	tooltip: {
		trigger: 'axis',
	},
	toolbox: {
		feature: {
			saveAsImage: {
				name: '设备属性',
			},
		},
	},
	legend: { show: true },
	xAxis: {
		type: 'category',
		boundaryGap: false,
		data: [],
	},
	yAxis: {
		type: 'value',
	},
	dataZoom: [
		{
			type: 'inside',
			start: 0,
			end: 10,
			zoomLock: true,
		},
		{
			start: 0,
			end: 10,
			zoomLock: true,
		},
	],
	series: [
		{
			name: props.name,
			type: 'line',
			smooth: true,
			// areaStyle: {},
			data: [],
			connectNulls: false,
			symbol: 'circle',
			symbolSize: [6, 6],
			showSymbol: false,
			lineStyle: { width: 1 },
		},
	],
};
const setOptions = () => {
	const series: any = props.seriesData;
	options.xAxis.data = props.xAxisData as any;
	options.series[0].data = series;
	options.series[0].name = props.name;
	if (!instance) {
		instance = echarts.init(chartRef.value);
		const { removeEvent } = useEventListener({
			el: window,
			name: 'resize',
			listener: resizeFnPollute,
		});
		removeResizeFn = removeEvent;

		instance.setOption(options);
		return;
	}
	instance && instance.clear();
	instance.setOption(options);
};
function resize() {
	const config = {
		animation: {
			duration: 300,
			easing: 'quadraticIn',
		},
	};
	instance.resize(config);
}
onMounted(() => {
	setTimeout(() => {
		setOptions();
	}, 100);
});

const handleZoomLock = (zoomLock: boolean) => {
	instance.setOption({
		dataZoom: {
			zoomLock: zoomLock,
		},
	});
};
tryOnUnmounted(() => {
	removeResizeFn();
});
defineExpose({
	resizeFnPollute,
	handleZoomLock,
});
</script>
